package com.pzhu.common.security;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.pzhu.common.constant.Constant;
import com.pzhu.model.entity.Menu;
import com.pzhu.model.entity.Role;
import com.pzhu.model.entity.User;
import com.pzhu.model.help.ResponseResult;
import com.pzhu.model.vo.MenuVo;
import com.pzhu.service.MenuService;
import com.pzhu.service.RoleService;
import com.pzhu.service.UserService;
import com.pzhu.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 登录成功处理
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private MenuService menuService;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();

        String username=authentication.getName(); // 获取用户名
        userService.update(new UpdateWrapper<User>().set("login_date",new Date()).eq("username",username)); // 更新最后登录日期

        // 生成jwt token
        String token= JwtUtils.genJwtToken(username);

        User currentUser = userService.getByUserName(username);


        // 获取当前用户拥有的权限菜单
        // 获取角色
        List<Role> roleList = roleService.list(new QueryWrapper<Role>().inSql("id", "select role_id from hs_user_role where user_id=" + currentUser.getId()));

        // 设置角色
        currentUser.setRoles(roleList.stream().map(Role::getName).collect(Collectors.joining(",")));

        StringBuffer permsStr=new StringBuffer();

        // 获取菜单权限
        Set<Menu> menuSet = new HashSet<Menu>();
        for(Role role : roleList){
            List<Menu> sysMenuList = menuService.list(new QueryWrapper<Menu>().inSql("id", "select menu_id from hs_role_menu where role_id=" + role.getId()));
            for(Menu menu : sysMenuList){
                menuSet.add(menu);
                permsStr.append(menu.getPerms()+",");
            }
        }

        String perms[]= StringUtils.tokenizeToStringArray(permsStr.toString(),",");

        List<Menu> menuList = new ArrayList<>(menuSet); // 转成集合List

        menuList.sort(Comparator.comparing(Menu::getOrderNum));  // 排序

        List<MenuVo> menuVoList = menuService.buildTreeMenu(menuList); // 构造菜单树

        outputStream.write(JSONUtil.toJsonStr(ResponseResult.ok(Constant.LOGIN_SUCCESS)
                .put("authorization",token)
                .put("menuList",menuVoList)
                .put("currentUser",currentUser)
                .put("perms",perms)).getBytes("UTF-8"));

        outputStream.flush();
        outputStream.close();
    }



}
